<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const share = reactive({
  add: true,
  maxnum: 1,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    aspectRatio: 1,
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
// ----
const advs = reactive({
  add: true,
  maxnum: 0,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
// ----
const displays = [{
  value: '1',
  text: '左右滑动'
}, {
  value: '2',
  text: '上下滑动'
}]
const musics = ref([])
// ----
const form = reactive({
  name: '',
  // ----
  shareDesc: '',
  display: displays[0].value,
  displayText: displays[0].text,
  music: 0,
  musicTxt: '',
  isLink: false
})

/* ---- */
const pickerDisplay = ref()
const pickerMusic = ref()
const uploadoss = ref()
const layer = ref()
const layerLoading = ref()

/* ---- */
const getFormInfo = async () => {
  share.setTrueStyle = { height: `${document.querySelector('.ratioBox dl dd label').clientWidth / share.forFree}px` }
  advs.setTrueStyle = { height: `${document.querySelector('.squareBox dl dd label').clientWidth / advs.forFree}px` }
  // --获取背景音乐集--
  const musicItems = forSys.filter((item) => { return String(item.name) === 'market_bgMusic' })
  if (Number(musicItems.length) === 1) {
    await proxy.$Myfun.getJsonData(musicItems[0].value, (resJson) => {
      const newItems = []
      resJson[0].list.forEach((item) => {
        newItems.push({
          value: String(item.id),
          text: proxy.$Myfun.setText(item.name)
        })
      })
      musics.value = newItems
    })
  }
  // ----
  if (proxy.$route.query.id) {
    await proxy.$http.get('album-category/index', {
      params: { 'AlbumCategorySearch[id]': proxy.$route.query.id }
    }).then((res) => {
      const IData = res.items[0] || {}
      // ----
      form.name = IData.name
      form.isLink = Number(IData.is_invite) === 1
      // ----
      proxy.$Myfun.getJsonData(IData.remark, (resJson) => {
        const RJData = resJson[0] || {}
        if (RJData.description) form.shareDesc = RJData.description
        if (RJData.display_id) form.display = RJData.display_id
        if (RJData.music_id) form.music = RJData.music_id
        // ----
        RJData.share_img.forEach((item) => {
          share.imgs.push({
            imgName: item.name,
            imgUrl: item.image,
            imgW: item.width,
            imgH: item.height
          })
        })
        if (Number(share.imgs.length) >= Number(share.maxnum) && Number(share.maxnum) > 0) share.add = !share.add
        // ----
        RJData.albums.forEach((item) => {
          advs.imgs.push({
            imgName: item.name,
            imgUrl: item.image,
            imgW: item.width,
            imgH: item.height
          })
        })
        if (Number(advs.imgs.length) >= Number(advs.maxnum) && Number(advs.maxnum) > 0) advs.add = !advs.add
      })
    }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
    // ----
    displays.some((current) => {
      if (String(current.value) === String(form.display)) form.displayText = current.text
    })
    musics.value.some((current) => {
      if (String(current.value) === String(form.music)) form.musicTxt = current.text
    })
  }
}
// --上传图片操作--
const uploadAct = (type, selectObj, event, index) => {
  const uploadOss = uploadoss.value
  switch (Number(type)) {
    case 1: {
      uploadOss.uploadImg(event, selectObj,'imgs', index)
      break
    }
    case 2: {
      uploadOss.delInfo(selectObj, event)
      break
    }
    case 3: {
      uploadOss.uploadImgMoreWX(selectObj)
      break
    }
  }
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const options = {
        type: 1,
        button: ['取消', '确定'],
        initData: displays,
        yes: (result) => {
          form.displayText = result[0].text
          form.display = result[0].value
        }
      }
      proxy.$Myfun.isIndepth(pickerDisplay.value, 'open', options)
      break
    }
    case 2: {
      const options = {
        type: 1,
        isLimit: [{ value: '0', text: '不需背景音乐' }],
        button: ['取消', '确定'],
        initData: musics.value,
        yes: (result) => {
          form.musicTxt = Number(result[0].value) === 0 ? '' : result[0].text
          form.music = result[0].value
        }
      }
      proxy.$Myfun.isIndepth(pickerMusic.value, 'open', options)
      break
    }
  }
}
// ----
const subform = async () => {
  if (Number(form.name.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写标题名称！')
    return false
  }
  if (Number(form.displayText.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择展示方式！')
    return false
  }
  // ----
  const shareItems = []
  if (Number(share.imgs.length) > 0) {
    share.imgs.forEach((item) => {
      shareItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
  }
  // ----
  const advsItems = []
  if (Number(advs.imgs.length) > 0) {
    advs.imgs.forEach((item) => {
      advsItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH,
        title: '',
        content: ''
      })
    })
  }
  // ----
  const remarkObj = {
    description: form.shareDesc,
    share_img: shareItems,
    display_id: form.display,
    music_id: form.music,
    albums: advsItems
  }
  // ----
  const forRemark = JSON.stringify(remarkObj)
  // ----
  let forType = 'post'
  let forUrl = 'album-category/create'
  let forData = {
    dealer_id: logUser.id,
    // ----
    name: form.name,
    remark: forRemark,
    is_invite: form.isLink ? 1 : 0,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (proxy.$route.query.id) {
    forType = 'patch'
    forUrl = 'album-category/update?id=' + proxy.$route.query.id
    forData = {
      name: form.name,
      remark: forRemark,
      is_invite: form.isLink ? 1 : 0,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  if (resData) proxy.$router.back()
}
const goback = () => { proxy.$router.back() }

/* ---- */
onMounted(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <li>
          <div class="form-are xw-radius-3">
            <h1>标题名称</h1>
            <p><textarea class="tarea-H2" placeholder="" v-model.trim="form.name"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>简易描述</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.shareDesc"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 ratioBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">分享图标</span>
            </div>
            <dl class="FIS-img">
              <dd v-for="(item, index) in share.imgs"><label class="xw-block xw-act"><img :src="item.imgUrl"/><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, share, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, share, index)"></span></dd>
              <dd v-if="share.add"><label class="xw-act xw-flex xw-flex-center" :style="share.setTrueStyle"><em class="fal fa-plus"></em><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, share, $event)"/></label></dd>
            </dl>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 squareBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">图片列表（共{{Number(advs.imgs.length)}}张）</span>
              <span v-if="Number(advs.maxnum) > 0">数量：最多{{advs.maxnum}}张</span>
            </div>
            <dl class="FIS-img xw-float">
              <dd class="xw-float-W3" v-for="(item, index) in advs.imgs"><label class="xw-block xw-act" :style="advs.setTrueStyle"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.imgUrl + ')' }"></div><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, advs, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, advs, index)"></span></dd>
              <dd class="xw-float-W3" v-if="advs.add"><label class="xw-act xw-flex xw-flex-center" :style="advs.setTrueStyle" @click="uploadAct(3, advs)"><em class="fal fa-plus"></em></label></dd>
            </dl>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>展示方式</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="请选择展示方式" v-model.trim="form.displayText" @click="getAuditFun(1)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.displayText"></em></transition>
          </div>
        </li>
        <li v-if="Number(musics.length) > 0">
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>背景音乐</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="不需背景音乐" v-model.trim="form.musicTxt" @click="getAuditFun(2)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.musicTxt"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align xw-flex-justify">
            <i>移动门店购物链接</i>
            <p class="uct-sel"><input type="checkbox" class="a-switch" v-model="form.isLink"/></p>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <picker-view ref="pickerDisplay"/>
    <picker-view ref="pickerMusic"/>
    <uploadoss-view ref="uploadoss"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.uct-sel { height: 3rem; overflow: visible; }
</style>